package edu.bit.water.service;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import edu.bit.water.dao.EntitySensorDao;
import edu.bit.water.entity.EntitySensor;
import edu.bit.water.entity.EntityWater;
import edu.bit.water.util.DateTimeUtil;

import org.apache.poi.xssf.usermodel.XSSFPivotTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import edu.bit.water.dao.EntityWaterDao;
import edu.bit.water.dto.DateUtils;

@Service
public class EntityWaterService {

    @Autowired
    private EntityWaterDao entityWaterDao;

    @Autowired
    private EntitySensorDao entitySensorDao;

    public Map<String, Object> insertEntityWater(EntityWater entityWater) {
        Map<String, Object> modelMap = new HashMap<>();
        Integer id = entityWaterDao.getMaxId();

        if (id != null) {
            entityWater.setId(id + 1);
        } else {
            entityWater.setId(0);
        }
        try {
            entityWaterDao.insertEntityWater(entityWater);
            modelMap.put("status", "success");
            return modelMap;
        } catch (Exception e) {
            e.printStackTrace();
            modelMap.put("status", "failed");
            modelMap.put("msg", e.getClass());
        }
        return modelMap;
    }

    public Map<String, Object> importExcel() {
        Map<String, Object> modelMap = new HashMap<>();
        modelMap.put("status", "success");
        modelMap.put("msg", "hahaha");
        return modelMap;
    }

    /**
     * 实体水表删除数据
     *
     * @param idList 删除数据行的id
     * @return 成功返回1，失败返回0
     */
    public int deleteEntityWater(String idList) {
        return entityWaterDao.deleteEntityWater(idList);
    }

    /**
     * 实体水表查询数据
     * 将时间格式设为"yyyy-mm-dd hh:mm:ss"
     *
     * @return 成功返回1，失败返回0
     */
    public List<Map<String, Object>> selectEntityWater() {
        List<Map<String, Object>> sList = entityWaterDao.selectEntityWater();
        for (int i = 0; i < sList.size(); i++) {
            String time = DateTimeUtil.dateToStr((Date) sList.get(i).get("CREATED_AT"));
            sList.get(i).put("CREATED_AT", time);
        }
        return sList;
    }

    public List<Map<String, Object>> selectEntityWaterByCompanyId(String company_id) {
        List<Map<String, Object>> sList = entityWaterDao.selectEntityWaterByCompanyId(company_id);
        for (int i = 0; i < sList.size(); i++) {
            String time = DateTimeUtil.dateToStr((Date) sList.get(i).get("CREATED_AT"));
            sList.get(i).put("CREATED_AT", time);
        }
        return sList;
    }

    public List<Map<String, Object>> selectEntityWaterByCompanyIdAndSearch(String companyId, int begin, int end, String searchContent) {
        List<Map<String, Object>> sList = entityWaterDao.selectEntityWaterByCompanyIdAndSearchContent(companyId, begin, end, searchContent);
        for (int i = 0; i < sList.size(); i++) {
            String time = DateTimeUtil.dateToStr((Date) sList.get(i).get("CREATED_AT"));
            sList.get(i).put("CREATED_AT", time);
        }
        return sList;
    }

    public int selectEntityWaterSumByCompanyId(String companyId, String searchContent) {
        return entityWaterDao.selectEntityWaterSumByCompanyId(companyId, searchContent);
    }

    /**
     * 根绝企业id查询该企业各个设备最新的采集数值
     *
     * @param businessId
     * @return
     */
    public List<EntityWater> selectNewByBusinessId(String businessId) {
        List<EntityWater> sList = entityWaterDao.selectNewEntity(businessId);
        for (EntityWater sensor : sList) {

        }
        return sList;
    }

    public List<Map<String, Object>> selectEntityWaterByCompanyIdSensor(String company_id, String sensor) {
        List<Map<String, Object>> sList = entityWaterDao.selectEntityWaterByCompanyIdSensor(company_id, sensor);
        for (int i = 0; i < sList.size(); i++) {
            String time = DateTimeUtil.dateToStr((Date) sList.get(i).get("CREATED_AT"));
            sList.get(i).put("CREATED_AT", time);
        }
        return sList;
    }

    public int selectEntityWaterSumByCompanyIdSensor(String companyId, String sensor) {
        return entityWaterDao.selectEntityWaterSumByCompanyIdSensor(companyId, sensor);
    }

    public List<Map<String, Object>> selectEntityWaterByCompanyIdSensor__(String company_id, String sensor, int begin, int end, String searchContent) {
        List<Map<String, Object>> sList = entityWaterDao.selectEntityWaterByCompanyIdSensor__(company_id, sensor, begin, end, searchContent);
        for (int i = 0; i < sList.size(); i++) {
            String time = DateTimeUtil.dateToStr((Date) sList.get(i).get("CREATED_AT"));
            sList.get(i).put("CREATED_AT", time);
        }
        return sList;
    }

    /**
     * 实体水表更新数据
     *
     * @return 成功返回1，失败返回0
     */
    public Map<String, Object> updateEntityWater(EntityWater entityWater) {
        Map<String, Object> modelMap = new HashMap<>();

        try {
            entityWaterDao.updateEntityWater(entityWater);
            modelMap.put("status", "success");
            return modelMap;
        } catch (Exception e) {
            e.printStackTrace();
            modelMap.put("status", "failed");
            modelMap.put("msg", e.getClass());
        }
        return modelMap;
    }

    /**
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return 差值
     */
    public Double subtraction(String[] sensor_ids, Date startTime, Date endTime) {
        double minuend = 0;        //初始化被减数
        double reduction = 0;    //初始化减数
        for (String string : sensor_ids) {
            Double startTimeResult = entityWaterDao.subtraction(startTime, string);
            if (startTimeResult != null) {
                minuend += startTimeResult;
            }
            Double endTimeResult = entityWaterDao.subtraction(endTime, string);
            if (endTimeResult != null) {
                reduction += entityWaterDao.subtraction(endTime, string);
            }
        }
        return minuend - reduction;
    }

    public List<Map<String, Object>> selectEntityWaterByCondition(String SensorRowIds, String startTime, String endTime, String companyId) {
        List<Map<String, Object>> sList = entityWaterDao.selectEntityWaterByCondition(SensorRowIds, startTime, endTime, companyId);
        for (int i = 0; i < sList.size(); i++) {
            String time = DateTimeUtil.dateToStr((Date) sList.get(i).get("CREATED_AT"));
            sList.get(i).put("CREATED_AT", time);
        }
        return sList;
    }

    public List<String> querySensorRowIdsByTime(Date lastTime) {
        return entityWaterDao.querySensorRowIdsByTime(lastTime);
    }


    /**
     * 获取index页面需要的数据
     */
    public static void print(String s) {
    }

    public Map<String, Object> queryIndexData() {
        Map<String, Object> result = new HashMap<>();
        String now = DateUtils.getNowDate();
        String oneHourBefore = DateUtils.getBeforeNowOneHourDate();
        String oneWeekBefore = DateUtils.getBeforeNowOneWeekDate();
        String oneMonthBefore = DateUtils.getBeforeNowOneMonthDate();
        String oneDayBefore = DateUtils.getBeforeNowOneDayDate();
        int sumOfHour = entityWaterDao.queryIndexData(now, oneHourBefore);
        result.put("hour", sumOfHour);
        int sumOfDay = entityWaterDao.queryIndexData(now, oneDayBefore);
        result.put("day", sumOfDay);
        int sumOfWeek = entityWaterDao.queryIndexData(now, oneWeekBefore);
        result.put("week", sumOfWeek);
        int sumOfMonth = entityWaterDao.queryIndexData(now, oneMonthBefore);
        result.put("month", sumOfMonth);
        //print("now: " + now);
        //print("oneHourBefore: " + oneHourBefore);
        //print("oneWeekBefore: " + oneWeekBefore);
        //print("oneMonthBefore: " + oneMonthBefore);
        //print("oneDayBefore: " + oneDayBefore);
        return result;
    }

    public String queryValueBySensorRowId(String businessId, String sensorRowId) {
        List<Double> list = entityWaterDao.queryValueBySensorRowId(businessId, sensorRowId);
        if (list.size() == 0) {
            return "null";
        } else {
            return list.get(0).toString();
        }
    }

    public String queryNewValueBySensorRowId(String businessId, String sensorRowId) {
        List<Double> list = entityWaterDao.queryNewValueBySensorRowId(businessId, sensorRowId);
        if (list.size() == 0) {
            return "null";
        } else {
            return list.get(0).toString();
        }
    }


    /**
     * 数据迁移 data_collection to entity_water
     */
    public Map<String, Object> dataCollection() throws ParseException {
        List<Map<String, Object>> cList = entityWaterDao.getDataCollection();
        for (Map<String, Object> map : cList) {
            EntityWater entity = new EntityWater();
            entity.setValue(Float.parseFloat(map.get("VALUE").toString()));
            entity.setSensorRowId(map.get("ID").toString());
            entity.setTime(map.get("YEAR_MONTH").toString() + " " + map.get("TIME").toString());
            entity.setCreatedAt__(map.get("YEAR_MONTH").toString() + " " + map.get("TIME").toString());
            entity.setOperator(-1);
            entity.setWorkshop(entitySensorDao.queryWorkshopBySensorRowId(entity.getSensorRowId()));
            entity.setSensorType(entitySensorDao.queryTypeBySensorRowId(entity.getSensorRowId()));
            entity.setCompanyId(Integer.parseInt(entitySensorDao.queryTechprocessIdBySensorRowId(entity.getSensorRowId())));
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("status", "success");
        return resultMap;
    }


    /**
     * 将yearmonth的时间数据转换到created_at字段中
     */
    public void timeDataTransform() throws ParseException {
        List<Map<String, Object>> list = entityWaterDao.queryCreatedHasNull();
//        System.out.println(list.size());
//        for (Map<String, Object> item : list) {
//            System.out.println(item);
//        }
        if (list.size() > 0) {
            for (Map<String, Object> item : list) {
                try {
                    boolean flag = false;
                    EntityWater entity = new EntityWater();
                    entity.setId(Integer.parseInt(item.get("ID").toString()));
                    if (item.get("YEAR_MONTH") != null) {
                        entity.setCreatedAt__(item.get("YEAR_MONTH").toString());
                        flag = true;
                    }
                    EntitySensor entity_ = new EntitySensor();
                    entity_.setSensorRowId(item.get("SENSOR_ROW_ID").toString());
                    List<EntitySensor> listE = entitySensorDao.queryEntitySensor(entity_);
                    if (listE != null && !listE.isEmpty()) {
                        if (item.get("WORKSHOP") == null) {
                            entity.setWorkshop(listE.get(0).getWorkshop());
                        }
                        if (item.get("SENSOR_TYPE") == null) {
                            entity.setSensorType(listE.get(0).getSort());
                        }
                        if (item.get("COMPANY_ID") == null) {
                            entity.setCompanyId(Integer.parseInt(listE.get(0).getTechProcessId()));
                        }
                        flag = true;
                    } else {
                        entity.setWorkshop("未知");
                        entity.setSensorType("未查询到");
                        entity.setCompanyId(-1);
                    }
                    if (flag) {
                        entityWaterDao.updateEntityWater__(entity);
                    }
                } catch (Exception e) {
                    System.out.println(e);
                }
            }
        }
    }
}
